var CANVAS_W = 800;
var CANVAS_H = 600;
var DATA =  [[30, 0.7], [-30, 0.6]];
var SETTING = {start:{x:400, y:580}, angle:90.0, length:200};
var MAX_LEVEL = 7;

function main() {
	var ctx = document.getElementById('canvas').getContext('2d');
	draw_background(ctx, '#99cc33');
	ctx.strokeStyle = "white";
	ctx.fillStyle = "white";  
	draw_tree(ctx, SETTING, 1);
}
 
function point(x, y) {
	return {x:x, y:y}
}

function A2R(angle) {
	return angle * Math.PI / 180.0;
}

function draw_background(ctx, color) {
	ctx.fillStyle=color;
	ctx.fillRect(0, 0, CANVAS_W, CANVAS_H);
}

function draw_line(ctx, p1, p2) {
	ctx.moveTo(p1.x, p1.y);
	ctx.lineTo(p2.x, p2.y);
	ctx.stroke();
}

function line_end(p, l, angle) {
	var r = A2R(angle);
	return {x:p.x + l * Math.cos(r),
					y:p.y - l * Math.sin(r)}
}
 
function draw_tree(ctx, s, level) {
	var i;
	var a = s.angle;
	var l = s.length;
	var p = line_end(s.start, l, a);
	draw_line(ctx, s.start, p); 
	if(level <= MAX_LEVEL) {
		for(i = 0; i < DATA.length; ++i) {
			var b = DATA[i];
			var s2 = {start:p, angle:a + b[0], length:l * b[1]};
			draw_tree(ctx, s2, level + 1);
		}
	}
}

